//
//  FinishInfoViewController.m
//  51易借
//
//  Created by 张睿 on 2017/8/28.
//  Copyright © 2017年 张睿. All rights reserved.
//

#import "FinishInfoViewController.h"
#import "FinishTopView.h"
#import "FinishBottomView.h"
#import "FinishBasicCell.h"
#import "PersonalViewController.h"
#import "ContactViewController.h"
#import "MobileViewController.h"
#import "WorkInfoViewController.h"
#import "MoreInfoViewController.h"
#import "BankManagerViewController.h"
#import "FinishPageModel.h"
#import "MemberInfoModel.h"
#import "ZhiMaViewController.h"
#import "MobileVerifyViewController.h"
#import "BankDetailViewController.h"
#import "AppDelegate.h"
#import "MainViewController.h"
#import "HomeViewController.h"


@interface FinishInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)FinishPageModel * pgeModel;
@property (nonatomic, weak)UIView * topView;
@property (nonatomic, strong)FinishTopView * planView;
@property (nonatomic, strong)FinishBottomView * bottomView;
@property (nonatomic, weak)UIImageView * mustImageView;
@property (nonatomic, weak)UILabel * basicLabel;
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSArray * titleArray;
@property (nonatomic, weak)UIImageView * addImageView;
@property (nonatomic, weak)UILabel * addLabel;
@property (nonatomic, weak)UIButton * bottomButton;

@property (nonatomic,strong)MemberInfoModel * pageModel;
@property (nonatomic, assign)int currentStep;


@end

@implementation FinishInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupNavBar];
    [self setupUI];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getMemberDetail];

}



- (void)setupNavBar{
    
    self.title = @"完善资料";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}



- (void)setupUI{
    
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.titleArray = @[@"个人信息",@"紧急联系人",@"收款银行卡",@"芝麻授信",@"手机运营商"];
    
    self.view.backgroundColor = BACK_COLOR;
    
    UIView * topView = [UIView new];
    
    topView.backgroundColor = ColorWithRGB(0xff7907);
    
    self.topView = topView;
    
    [self.view addSubview:self.topView];
    
    
    self.planView = [FinishTopView new];
    
    [self.view addSubview:self.planView];
    
    
    UIImageView * mustImageView = [UIImageView new];
    
    mustImageView.image = [UIImage imageNamed:@"基础认证"];
    
    self.mustImageView = mustImageView;
    
    [self.view addSubview:self.mustImageView];
    
    
    UILabel * basicLabel = [UILabel new];
    
//    basicLabel.font = [UIFont fontWithName:TYPE_FACE size:13 * SCREENH6];
    basicLabel.font = [UIFont systemFontOfSize:13.5 * SCREENH6];
    basicLabel.textColor = ColorWithRGB(0x7f7f7f);
    basicLabel.text = @"基础认证（必填）";
    
    self.basicLabel = basicLabel;
    
    [self.view addSubview:self.basicLabel];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(6, 215 * SCREENH6, SCREEN_WIDTH - 12 * SCREENH6, 240 * SCREENH6)];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.bounces = NO;
    
    [self.tableView registerClass:[FinishBasicCell class] forCellReuseIdentifier:@"finishCell"];
    
    [self.view addSubview:self.tableView];
    
    
    UIImageView * addImageView = [UIImageView new];
    
    addImageView.image = [UIImage imageNamed:@"加分认证"];
    
    self.addImageView = addImageView;
    
    [self.view addSubview:self.addImageView];
    
    
    UILabel * addLabel = [UILabel new];
    
//    addLabel.font = [UIFont fontWithName:TYPE_FACE size:13 * SCREENH6];
    addLabel.font = [UIFont systemFontOfSize:13.5 * SCREENH6];
    addLabel.textColor = ColorWithRGB(0x7f7f7f);
    addLabel.text = @"加分认证（选填，可提高额度）";
    
    self.addLabel = addLabel;
    
    [self.view addSubview:self.addLabel];
    
    
    self.bottomView = [FinishBottomView new];
    [self.bottomView setWorkBLock:^{

            HIDDEN_TAB;
            
            WorkInfoViewController * workVC = [WorkInfoViewController new];
            
            [self.navigationController pushViewController:workVC animated:YES];

    }];
    [self.bottomView setMoreBlock:^{
        
        HIDDEN_TAB;
        
        MoreInfoViewController * moreVC = [MoreInfoViewController new];
        
        [self.navigationController pushViewController:moreVC animated:YES];
    }];
    [self.view addSubview:self.bottomView];
    
    
    UIButton * bottomButton = [UIButton new];
    //300 * 42
    [bottomButton setTitle:@"查看借款额度" forState:UIControlStateNormal];
    [bottomButton setBackgroundImage:[UIImage imageNamed:@"去还款"] forState:UIControlStateNormal];
    [bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bottomButton addTarget:self action:@selector(didbottomButton) forControlEvents:UIControlEventTouchUpInside];
    bottomButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    bottomButton.hidden = YES;
    
    self.bottomButton = bottomButton;
    
    [self.view addSubview:self.bottomButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(64);
    }];
    
    [self.planView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topView.mas_bottom).offset(10 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(6 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-6 * SCREENH6);
        make.height.mas_equalTo(104 * SCREENH6);
    }];
    
    [self.mustImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.planView);
        make.top.mas_equalTo(self.planView.mas_bottom).offset(9 * SCREENH6);
        make.width.height.mas_equalTo(17 * SCREENH6);
    }];
    
    [self.basicLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.mustImageView.mas_trailing).offset(5 * SCREENH6);
        make.centerY.mas_equalTo(self.mustImageView);
    }];
    
    [self.addImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.with.height.mas_equalTo(self.mustImageView);
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(9 * SCREENH6);
    }];
    
    [self.addLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.basicLabel);
        make.centerY.mas_equalTo(self.addImageView);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.tableView);
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(37 * SCREENH6);
        make.height.mas_equalTo(98 * SCREENH6);
    }];
    
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.bottomView.mas_bottom).offset(25 * SCREENH6);
        make.width.mas_equalTo(300 * SCREENH6);
        make.height.mas_equalTo(42 * SCREENH6);
    }];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.titleArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FinishBasicCell * cell = [tableView dequeueReusableCellWithIdentifier:@"finishCell" forIndexPath:indexPath];
    
    cell.titleLabel.text = self.titleArray[indexPath.row];
    
    if (indexPath.row == 4) {
        
        cell.lineView.hidden = YES;
    }
    switch (indexPath.row) {
        case 0:
        {
            cell.rightLabel.textColor = [self.pgeModel.personalInfoStatus intValue]==0?[UIColor redColor]:ColorWithRGB(0x7f7f7f);
            cell.rightLabel.text =[self.pgeModel.personalInfoStatus intValue]==0?@"未完善":@"已完善";
        }
            break;
        case 1:
        {
            cell.rightLabel.textColor = [self.pgeModel.emergencyStatus intValue]==0?[UIColor redColor]:ColorWithRGB(0x7f7f7f);
            cell.rightLabel.text =[self.pgeModel.emergencyStatus intValue]==0?@"未完善":@"已完善";

        }
            break;
        case 2:
        {
            cell.rightLabel.textColor = [self.pgeModel.bankCardStatus intValue]==0?[UIColor redColor]:ColorWithRGB(0x7f7f7f);
            switch ([self.pgeModel.bankCardStatus intValue]) {
                case 0:
                {
                    cell.rightLabel.text =@"未绑卡";
                }
                    break;
                case 1:
                {
                    cell.rightLabel.text =@"绑卡中";
                }
                    break;
                default:
                {
                    NSString*number = self.pgeModel.bankCardNo.length>=4?[self.pgeModel.bankCardNo substringFromIndex:self.pgeModel.bankCardNo.length-4]:self.pgeModel.bankCardNo;
                    cell.rightLabel.text =[NSString stringWithFormat:@"%@(%@)",self.pgeModel.bankName,number];
                }
                    break;
            }
        }
            break;
        case 3:
        {
            cell.rightLabel.textColor = [self.pgeModel.zhimaCreditStatus intValue]==0?[UIColor redColor]:ColorWithRGB(0x7f7f7f);
            cell.rightLabel.text =[self.pgeModel.zhimaCreditStatus intValue]==0?@"未授权":@"已授权";

        }
            break;
            
        default:{
            cell.rightLabel.textColor = [self.pgeModel.operatorStatus intValue]==0?[UIColor redColor]:ColorWithRGB(0x7f7f7f);
            switch ([self.pgeModel.operatorStatus intValue]) {
                case 0:
                {
                    cell.rightLabel.text =@"未认证";
                    cell.rightLabel.textColor =[UIColor redColor];
                }
                    break;
                case 1:
                {
                    cell.rightLabel.text =@"认证中";
                    cell.rightLabel.textColor =ColorWithRGB(0x7f7f7f);

                }
                    break;
                case 2:
                {
                    cell.rightLabel.text =@"认证失败";
                    cell.rightLabel.textColor =[UIColor redColor];

                }
                    break;
                default:
                {
                    cell.rightLabel.text =@"已认证";
                    cell.rightLabel.textColor =ColorWithRGB(0x7f7f7f);

                }
                    break;
        }
            break;
    }
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 48 * SCREENH6;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HIDDEN_TAB;
    if(self.pgeModel){
    if (indexPath.row == 0) {
        
        PersonalViewController * personVC = [PersonalViewController new];
        personVC.currentStep = self.currentStep;
        
        [self.navigationController pushViewController:personVC animated:YES];
    }else if (indexPath.row == 1){
        
        if (self.currentStep >= 2) {
        
            ContactViewController * contactVC = [ContactViewController new];
            contactVC.currentStep = self.currentStep;
            
            [self.navigationController pushViewController:contactVC animated:YES];
            
        }else{
            
            [self showHint:@"请先完善个人信息"];
        }
        
    }else if (indexPath.row == 2){
        
        if (self.currentStep >= 3) {
        
            if(self.pgeModel.bankCardNo.length)
            {
                BankDetailViewController* bankVC = [BankDetailViewController new];
                
                [self.navigationController pushViewController:bankVC animated:YES];
            }else{
                BankManagerViewController * bankVC = [BankManagerViewController new];
                
                [self.navigationController pushViewController:bankVC animated:YES];
            }
        }else if (self.currentStep == 1){
            
            [self showHint:@"请先完善个人信息"];
        }else{
            
            [self showHint:@"请先绑定紧急联系人"];
        }
        
        
    }else if (indexPath.row == 3)
    {
        if (self.currentStep >= 4) {
        
            if([self.pgeModel.zhimaCreditStatus integerValue]==3)
            {
                [self showHint:@"已授权"];
                
                return;
            }
            [self getApplyZhima:^(NSString *url) {
                ZhiMaViewController * bankVC = [ZhiMaViewController new];
                bankVC.url = url;
                [self.navigationController pushViewController:bankVC animated:YES];
                
            }];
        }else if (self.currentStep == 1){
            
            [self showHint:@"请先完善个人信息"];
        }else if (self.currentStep == 2){
            
            [self showHint:@"请先绑定紧急联系人"];
        }else{
            
            [self showHint:@"请先绑定收款银行卡"];
        }

    }else
    {
        if (self.currentStep >= 5) {
        
            switch ([self.pgeModel.operatorStatus integerValue]) {
                case 0:
                {
                    MobileVerifyViewController*vc = [MobileVerifyViewController new];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case 1:
                {
                    [self showHint:@"认证中"];
                }
                    break;
                case 2:
                {
                    MobileVerifyViewController*vc = [MobileVerifyViewController new];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case 3:
                {
                    [self showHint:@"已认证"];
//                    MobileVerifyViewController*vc = [MobileVerifyViewController new];
//                    vc.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                default:
                    break;
            }
        }else if (self.currentStep == 1){
            
            [self showHint:@"请先完善个人信息"];
        }else if (self.currentStep == 2){
            
            [self showHint:@"请先绑定紧急联系人"];
        }else if (self.currentStep == 3){
            
            [self showHint:@"请先绑定收款银行卡"];
        }else{
            
            [self showHint:@"请先完成芝麻授信"];
        }
    }
    
    }
}




-(void)getApplyZhima:(void(^)(NSString*url))complete
{
    ParaModel*para = [ParaModel new];
    
    
    [[NetworkTool shareManager] POST:[Interfacefile getZhimaAuthorizeUrl] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            complete([responseObject objectForKey:@"data"]);
        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
    
}








//点击进入工作信息
- (void)pushWorkInfoVC{
    
  
}


//点击进入更多信息
- (void)pushMoreInfoVC{
   
}


- (void)didbottomButton{
    
//    self.tabBarController.selectedIndex = 0;
    
//    [self.navigationController popViewControllerAnimated:NO];
    
//    for (UIViewController *controller in self.navigationController.viewControllers) {
//        if ([controller isKindOfClass:[HomeViewController class]]) {
//            HomeViewController *revise =(HomeViewController *)controller;
//            [self.navigationController popToViewController:revise animated:YES];
//        }
//    }
    if ([self.setUp isEqualToString:@"setUp"]) {
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        MainViewController *tabs = [[MainViewController alloc] init];
        
        tabs.selectedIndex = 2;
        
        appDelegate.window.rootViewController = tabs;
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (void)backToLastView{
   
    if ([self.setUp isEqualToString:@"setUp"]) {
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        MainViewController *tabs = [[MainViewController alloc] init];
        
        tabs.selectedIndex = 2;
        
        appDelegate.window.rootViewController = tabs;
    }else{
        
       [self.navigationController popViewControllerAnimated:YES];
    }
}


//将通知中心移除

- (void)dealloc{
    
    // 移除当前所有通知
//    NSLog(@"移除了所有的通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getMemberDetail
{
    ParaModel*para = [ParaModel new];
    
    
    [[NetworkTool manager] POST:[Interfacefile getDataCompletePercent] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        
//        NSLog(@"==%@",responseObject);
        
        if([[responseObject objectForKey:@"code"] intValue]==0)
        {
            self.pgeModel = [[FinishPageModel alloc] initWithDictionary:[responseObject objectForKey:@"data"] error:nil];
            
//            NSString * currentStep = [NSString stringWithFormat:@"%@",currentStep];
            
            [self updateView];

        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
    
}


-(void)updateView
{
    self.planView.step = [self.pgeModel.currentStep intValue] - 1;
    
    self.currentStep = [self.pgeModel.currentStep intValue];
    
    [self.tableView reloadData];
    
    self.bottomView.workValueLabel.textColor =[self.pgeModel.workInfoStatus intValue]==0?[UIColor redColor]:ColorWithRGB(0x7f7f7f);
    self.bottomView.workValueLabel.text =[self.pgeModel.workInfoStatus intValue]==0?@"未完善":@"已完善";

    self.bottomView.moreInfoValueLabel.textColor =[self.pgeModel.extraInfoStatus intValue]==0?[UIColor redColor]:ColorWithRGB(0x7f7f7f);
    self.bottomView.moreInfoValueLabel.text =[self.pgeModel.extraInfoStatus intValue]==0?@"未完善":@"已完善";

    if (self.currentStep >= 6) {
        
        self.bottomButton.hidden = NO;
    }else{
        
        self.bottomButton.hidden = YES;
    }
}







@end
